import { defineComponent, PropType, ref, VNode } from 'vue';
import { useNamespace } from '@ibiz-template/vue3-util';
import {
  IDrawerOptions,
  IModalData,
  IOverlayContainer,
  Modal,
  ViewMode,
} from '@ibiz-template/runtime';
import { OverlayContainer } from '../overlay-container/overlay-container';
import './app-drawer-component.scss';
import { useUIStore } from '../store';

export const AppDrawerComponent = defineComponent({
  props: {
    opts: {
      type: Object as PropType<IDrawerOptions>,
      default: () => ({}),
    },
  },
  setup(props, ctx) {
    const ns = useNamespace('drawer');

    const isShow = ref(false);

    let data: IData;

    const { zIndex } = useUIStore();
    const drawerZIndex = zIndex.increment();

    const modal = new Modal({
      mode: ViewMode.DRAWER,
      viewUsage: 2,
      dismiss: (_data: IModalData) => {
        zIndex.decrement();
        isShow.value = false;
        data = _data;
      },
    });

    // 自身的所有关闭方式最终都走这个
    const onBeforeClose = async (done: () => void) => {
      const isClose = await modal.dismiss();
      if (isClose) {
        done();
      }
    };

    // 外部函数式调用
    const dismiss = (_data?: IModalData) => {
      modal.dismiss(_data);
    };

    const present = () => {
      isShow.value = true;
    };

    // 完全关闭后调用销毁
    const onClosed = () => {
      ctx.emit('dismiss', data);
    };

    let direction = '';

    switch (props.opts.placement) {
      case 'left':
        direction = 'ltr';
        break;
      case 'top':
        direction = 'ttb';
        break;
      case 'bottom':
        direction = 'btt';
        break;
      default:
        direction = 'rtl';
    }

    return {
      ns,
      isShow,
      direction,
      drawerZIndex,
      modal,
      dismiss,
      present,
      onClosed,
      onBeforeClose,
    };
  },
  render() {
    return (
      <el-drawer
        model-value={this.isShow}
        lock-scroll
        with-header={false}
        size={this.opts.width}
        class={this.ns.b()}
        z-index={this.drawerZIndex}
        direction={this.direction}
        before-close={this.onBeforeClose}
        onClosed={this.onClosed}
      >
        {this.$slots.default?.(this.modal)}
      </el-drawer>
    );
  },
});

/**
 * 创建抽屉
 *
 * @author chitanda
 * @date 2022-12-29 15:12:57
 * @export
 * @param {() => VNode} render
 * @param {(IDrawerOptions | undefined)} [opts]
 * @return {*}  {IOverlayContainer}
 */
export function createDrawer(
  render: () => VNode,
  opts?: IDrawerOptions | undefined,
): IOverlayContainer {
  return new OverlayContainer(AppDrawerComponent, render, opts);
}
